package com.shoesdemo.activity;

import android.content.Intent;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shoesdemo.BaseActivity;
import com.shoesdemo.R;
import com.shoesdemo.data.ImageInfo;
import com.shoesdemo.view.photoview.PhotoView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class PictureActivity extends BaseActivity {
    String url = "http://cn.bing.com/HPImageArchive.aspx";
    private PhotoView mPhotoView;
    private String mImageUrl;

    @Override
    protected void initView() {
        mPhotoView = findViewById(R.id.photoview);
        mView.setBackgroundColor(getResources().getColor(R.color.color_black));
        setTitle("每日一图");
        setRightIcon(R.mipmap.icon_share_with);
    }

    @Override
    public void setRightClick(View view) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain"); //分享的是文本类型
        shareIntent.putExtra(Intent.EXTRA_TEXT, mImageUrl);//分享出去的内容
        startActivity(shareIntent);    //注意这里的变化
    }

    @Override
    protected void initListener() {

    }

    @Override
    public int getLayoutView() {
        return R.layout.activity_picture;
    }

    @Override
    protected void initData() {
        OkHttpUtils.get().url(url)
                .addParams("format", "js")
                .addParams("idx", 0 + "")
                .addParams("n", 1 + "")
                .build().execute(new StringCallback() {


            @Override
            public void onError(okhttp3.Call call, Exception e, int id) {
                Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    JSONArray images = jsonObject.optJSONArray("images");
                    Gson gson = new Gson();
                    List<ImageInfo> imageInfos = gson.fromJson(images.toString(), new TypeToken<List<ImageInfo>>() {
                    }.getType());
                    if (imageInfos.size() > 0) {
                        mImageUrl = "http://s.cn.bing.net"+imageInfos.get(0).getUrl();
                        Glide.with(mContext)
                                .load(mImageUrl)
                                .into(mPhotoView);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
